<?php

namespace Dls\Entity\V0\Grid;


use Dls\Entity\V0\Grid;
use Dls\Entity\V0\Grid\Exporters\AbstractExporter;
use Dls\Entity\V0\Grid\Exporters\CsvExporter;

class Exporter
{

    /**
     * Export scope constants.
     */
    const SCOPE_ALL = 'all';

    /**
     *
     * @var
     */
    public static $queryName = '_export_';

    /**
     * @var Grid
     */
    protected $grid;
    /**
     * Available exporter drivers.
     *
     * @var array
     */
    protected static $drivers = [];

    /**
     * Create a new Exporter instance.
     *
     * @param Grid $grid
     */
    public function __construct(Grid $grid)
    {
        $this->grid = $grid;
        $this->grid->model()->usePaginate(false);
    }

    /**
     * Extends new exporter driver.
     *
     * @param $driver
     * @param $extend
     */
    public static function extend($driver, $extend)
    {
        static::$drivers[$driver] = $extend;
    }
    /**
     * Resolve export driver.
     *
     * @param string $driver
     *
     * @return AbstractExporter
     */
    public function resolve($driver)
    {
        if ($driver instanceof Grid\Exporters\AbstractExporter) {
            return $driver->setGrid($this->grid);
        }
        return $this->getExporter($driver);
    }
    /**
     * Get export driver.
     *
     * @param string $driver
     *
     * @return CsvExporter
     */
    protected function getExporter($driver)
    {
        if (!array_key_exists($driver, static::$drivers)) {
            return $this->getDefaultExporter();
        }
        return new static::$drivers[$driver]($this->grid);
    }
    /**
     * Get default exporter.
     *
     * @return CsvExporter
     */
    public function getDefaultExporter()
    {
        return new CsvExporter($this->grid);
    }

    /**
     * Format query for export url.
     *
     * @param string|array $queryConditions
     * @return string
     */
    public static function formatExportQuery($queryConditions)
    {
        $query[self::$queryName] = self::SCOPE_ALL;
        if (is_string($queryConditions)) {
            return http_build_query($query) . '&' . substr($queryConditions, strrpos($queryConditions, '?') + 1);
        }

        /*
         * example 1：
         *  ['user_id', 'created_time'] => user_id=<{user_id}>&created_time=<{created_time}>
         *
         * example 2:
         *  ['user_id', ['type' => 'value']] => user_id=<{user_id}>&<{type}>=<{value}>
         *
         */
        foreach ($queryConditions as $condition) {
            if (is_array($condition)) { //
                $key = key($condition);
                $query["<{{$key}}>"] = "<{{$condition[$key]}}>";
            } else {
                $query[$condition] = "<{{$condition}}>";
            }
        }

        return urldecode(http_build_query($queryConditions));
    }


}